const express = require('express');
const router = express.Router();
const { Chapter, Course, User } = require('../models');
const { success, failure } = require('../utils/responses');
const { NotFound, Forbidden } = require('http-errors');
const chapter = require('../models/chapter');

/**
 * 查询分类
 *
 * GET /categories
 * */

router.get('/:id', async function (req, res) {
  try {
    const { id } = req.params;
    // const condition = {
    //     attributes: { exclude: ['CourseId']},
    //     include: [
    //         {
    //             model: Course,
    //             as: 'course',
    //             attributes: ['id', 'name'],
    //             include: [
    //                 {
    //                     model: User,
    //                     as: 'user',
    //                     attributes: ['id', 'username', 'nickname','avatar','company']
    //                 }
    //             ]
    //         }
    //     ]
    // }
    const chapter = await Chapter.findByPk(id, {
      attributes: { exclude: ['CourseId'] },
    });

    const course = await chapter.getCourse({
      attributes: ['id', 'name', 'userId'],
    });
    const user = await course.getUser({
      attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
    });
    if (!chapter) {
      throw new NotFound(`ID: ${id} 的章节未找到`);
    }

    await checkUserRole(req, chapter);

    const chapters = await Chapter.findAll({
      attributes: { exclude: ['CourseId', 'content'] },
      where: { courseId: chapter.courseId },
      order: [
        ['rank', 'asc'],
        ['id', 'desc'],
      ],
    });

    success(res, '查询成功', { chapter, chapters, user, course });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 检查用户是否能浏览当前章节
 * @param req
 * @param chapter
 * @returns {Promise<void>}
 * */

async function checkUserRole(req, chapter) {
  // 如果章节是免费的
  if (chapter.free) {
    return;
  }
  const allowedRoles = [1, 100]; // 大会员和管理员的角色ID
  const user = await User.findByPk(req.userId);
  if (!allowedRoles.includes(user.role)) {
    throw new Forbidden('您没有权限浏览， 请先购买大会员后再访问');
  }
}

module.exports = router;
